<template>
  <div>
    <el-table
      v-loading="tableLoading"
      row-key="id"
      header-row-class-name="custom-table-header"
      :data="tableData"
    >
      <el-table-column
        label="参数名称"
        prop="name"
      >
        <template #default="{row}">
          <el-input v-if="row.edit" v-model="row.name" placeholder="参数名称如：数据库" />
          <span v-else>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="参数值"
        prop="value"
      >
        <template #default="{row}">
          <el-input v-if="row.edit" v-model="row.value" placeholder="参数值如：mysql5.7" />
          <span v-else>{{ row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        prop="action"
        width="200"
      >
        <template #default="{row}">
          <template v-if="row.edit">
            <span v-if="row.isNew">
              <el-button type="text" @click="saveRow(row)">添加</el-button>
              <el-popconfirm title="是否要删除此行？" @confirm="remove(row.id)">
                <template #reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </span>
            <span v-else>
              <el-button type="text" @click="saveRow(row)">保存</el-button>
              <el-button type="text" @click="cancel(row)">取消</el-button>
            </span>
          </template>
          <span v-else>
            <el-button type="text" @click="toggle(row.id)">编辑</el-button>
            <el-popconfirm title="是否要删除此行？" @confirm="remove(row.id)">
              <template #reference>
                <el-button type="text">删除</el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>

    </el-table>

    <el-button style="width: 100%;margin-top: 16px; border-style: dashed;" @click="newTableData">
      <i class="el-icon-plus" />
      新增环境参数
    </el-button>
    <div class="dialong__button--wrap">
      <el-button @click="close">取消</el-button>
      <el-button :loading="subLoading" type="primary" @click="setEnvironmen">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, PropType, ref, unref, watch } from 'vue'
import { InfoWriteParams } from './types'
import { delsApi, getDetApi, setApi, setEnvironmenApi } from '../api'
import { Message } from '_c/Message'

export default defineComponent({
  name: 'Detail',
  props: {
    info: {
      type: Object as PropType<any>,
      default: () => null
    }
  },
  emits: ['close', 'saveNewData'],
  setup: function(props, { emit }) {
    const form = reactive<InfoWriteParams>({
      id: '', // id
      subjectId: 0, // 课程所示栏目
      title: '', // 长标题
      shortTitle: '', // 短标题
      price: 0, // 价格
      lessonNum: 0, // 课时
      courseDesc: '', // 课程描述
      courseType: 0, // 课程类型
      difficulty: 0, // 课程难度
      remarks: '' // 课程详情
    })
    const formRef = ref<HTMLElement | null>(null)
    const editorRef = ref<HTMLElement | null>(null)
    const subLoading = ref<boolean>(false)
    const tableData = ref<any[]>([])
    const tableLoading = ref<boolean>(false)

    async function getDet() {
      if (props.info) {
        const id = (props.info as any).id
        try {
          const res = await getDetApi({
            params: {
              id: id
            }
          })
          if (res.code === 0) {
            tableData.value = res.data.environmenParams
            console.log('tableData.value', tableData.value)
          }
        } catch (e) {
          console.log(e)
        }
      }
    }

    getDet()

    // 新增内容
    const newIndex = ref<number>(0)
    const newTableData = () => {
      const newData = tableData.value.map(item => ({ ...item }))
      newData.push({
        id: newIndex.value,
        value: '',
        name: '',
        edit: true,
        isNew: true,
        courseId: (props.info as any).id
      })

      newIndex.value--
      tableData.value = newData
    }

    // 添加、保存
    const saveRow = (record: { id: any; name: any; value: any }) => {
      tableLoading.value = true
      const { id, name, value } = record
      if (!name || !value) {
        tableLoading.value = false
        Message.error('请填写完整环境信息。')
        return
      }

      const target: any = tableData.value.find(item => item.id === id)
      if (target) {
        target.edit = false
        target.isNew = false
        target._originalData = undefined
      }
      tableLoading.value = false
      const newData = tableData.value.map(item => ({ ...item }))
      console.info('添加或保存', newData)
    }

    // 新增或者编辑
    async function setEnvironmen() {
      try {
        const res = await setEnvironmenApi({
          data: tableData.value
        })
        if (res) {
          Message.success(form.id ? '编辑成功' : '新增成功')
          close()
        }
      } catch (err) {
        console.log(err)
      } finally {
        subLoading.value = false
      }
    }

    function close() {
      emit('close')
    }

    // 删除
    const remove = async(key: number) => {
      const newData = tableData.value.filter(item => item.id !== key)
      if (key > 0) { // 同时删除数据库里的数据
        const res = await delsApi({
          data: JSON.stringify(key)
        })
        if (res.code === 0) {
          tableData.value = newData
          Message.success(res.message)
        }
      }
    }

    // 取消编辑
    const cancel = (key: any) => {
      const target: any = tableData.value.find(item => item.id === key.id)
      if (target) {
        target._originalData = { ...target }
        target.edit = !target.edit
      }
    }

    // 编辑显示
    const toggle = (key: number) => {
      const target: any = tableData.value.find(item => item.id === key)
      target._originalData = { ...target }
      target.edit = !target.edit
    }

    watch(tableData.value, () => {
      const newData = tableData.value.map(item => ({ ...item }))
      tableData.value = newData
      console.log('tableData.value,watch:', tableData.value)
    })

    return {
      formRef, editorRef,
      form,
      close,
      subLoading,
      newTableData,
      tableData,
      tableLoading,
      saveRow,
      setEnvironmen,
      toggle,
      cancel,
      remove
    }
  }
})
</script>

<style>
</style>
